const Jpushs = require('./Jpushs')




const getJpushState=async (uid) => {

    let res=await Jpushs.findOne({uid})

    return res

}
exports.getJpushState=getJpushState


const saveJpushState=async (uid,is_on) => {

    let obj={
        uid,
        is_on
    }
    let res=new Jpushs(obj)

    await res.save()

    return ''

}
exports.saveJpushState=saveJpushState


const updateJpushState=async (uid,is_on) => {

    let obj={
        uid,
        is_on
    }

    await Jpushs.update({uid:uid}, obj)

    return ''

}
exports.updateJpushState=updateJpushState


exports.setJpushState=async (uid,is_on) => {

    let res=await getJpushState(uid)

    if(res){
        updateJpushState(uid,is_on)
    }
    else{
        saveJpushState(uid,is_on)
    }
    return ''
}



const removeGroupFromList=function (group_off_list,gid) {
    var index=-1
    for(let i=0; i<group_off_list.length; i++){
        let item=group_off_list[i]
        if(item==gid){
            index=i
            break;
        }
    }

    if(index>-1){
        group_off_list.splice(index,1)
    }

    return group_off_list

}



const updateJpushForGroup=async (uid,gid,group_is_on) => {
    let res=await Jpushs.findOne({uid})
    let group_off_list=res.group_off_list
    if(!group_off_list){
        group_off_list=[]
    }

    let new_list=[]
    if(group_is_on){  //1
        new_list=removeGroupFromList(group_off_list,gid)
    }
    else{   //0
        group_off_list.push(gid)
        new_list=group_off_list
    }

    let updata_list = [...new Set(new_list)]

    let obj={
        uid,
        group_off_list:updata_list
    }

    await Jpushs.update({uid:uid}, obj)

    return ''

}
exports.updateJpushForGroup=updateJpushForGroup



const saveJpushForGroup=async (uid,gid,group_is_on) => {
    let list=[]
    if(!group_is_on){
        list=[gid]
    }
    let obj={
        uid,
        group_off_list:list
    }
    let res=new Jpushs(obj)

    await res.save()

    return ''

}
exports.saveJpushForGroup=saveJpushForGroup



const gidInGroupList=(group_off_list,gid)=>{
    var index=-1
    for(let i=0; i<group_off_list.length; i++){
        let item=group_off_list[i]
        if(item==gid){
            index=i
            break;
        }
    }
    return index
}



exports.getGroupJpush=async (uid,gid) => {

    let res=await Jpushs.findOne({uid})

    let group_is_on=1
    if(res){
        let index=gidInGroupList(res.group_off_list,gid)
        if(index>-1){
            group_is_on=0
        }
    }

    return group_is_on
}



exports.setGroupJpush=async (uid,gid,group_is_on) => {

    let res=await getJpushState(uid)

    if(res){
        updateJpushForGroup(uid,gid,group_is_on)
    }
    else{
        saveJpushForGroup(uid,gid,group_is_on)
    }
    return ''
}









